package com.chenxy.gateway.config;

import feign.codec.Decoder;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * feign 配置类，不加这个gateway虽然能远程调用，但是返回数据会报错
 * @author chenxy
 */
@SpringBootConfiguration
public class OpenFeignConfig {

    @Bean
    public Decoder feignDecoder()
    {
        return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
    }

    public ObjectFactory<HttpMessageConverters> feignHttpMessageConverter()
    {
        final  HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new HttpMessageConverter[] { new GateWayMappingJackson2HttpMessageConverter() });
        return new ObjectFactory<HttpMessageConverters>(){
            @Override
            public HttpMessageConverters getObject() throws BeansException {
                return httpMessageConverters;
            }
        };
    }

    public class GateWayMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter
    {
        GateWayMappingJackson2HttpMessageConverter()
        {
            List<MediaType> mediaTypes = new ArrayList();
            mediaTypes.add(MediaType.valueOf("text/html;charset=UTF-8"));
            setSupportedMediaTypes(mediaTypes);
        }
    }
}
